﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;
using Acando.Dynamics.CRM.Silverlight.Library.Helper;
using System.Windows.Data;
using Acando.Dynamics.CRM.Silverlight.Library.Converter;
using Acando.Dynamics.CRM.Silverlight.Library.Controls;
using System.ComponentModel;
using Acando.Dynamics.CRM.Silverlight.Library.Interfaces;


using Acando.Dynamics.CRM.Silverlight.Library.MetaSdk;

namespace Acando.Dynamics.CRM.Silverlight.Library.Controls.FieldControls
{
    public enum DropdownType { Picklist, StatusReason }

    public partial class CrmPicklistControl : BaseValueControl
    {       

        #region Properties

        private List<Option> SelectableOptions { get; set; }
        //private ObservableCollection<Option> SelectableOptions  { get; set; }

        //private RadComboBox cmbPicklist { get; set; }   
        private AttributeMetadata AttrMeta { get; set; }
        private DropdownType DropdownType { get; set; }

        #endregion

        #region Constructor

        public CrmPicklistControl(IRecordControl recordControl, EntityMetadata metadata, string fieldName, string controlType, DropdownType dropdowntype)
            : base(recordControl,controlType,fieldName)
        {
            InitializeComponent();

            this.DropdownType = dropdowntype;
            
            this.RecordControl.RegisteredPicklists[fieldName] = this;

            //Fill Picklist
            if (metadata.AttributesDict().Keys.Contains(fieldName))
            {
                this.AttrMeta = metadata.AttributesDict()[fieldName];
                this.SelectableOptions = new List<Option>();
                this.ResetOptions();
            }
            
            
            this.cmbNew.ItemsSource = this.SelectableOptions;
            //this.cmbNew.DisplayMemberPath = "labelField.userLocLabelField.labelField";
            this.cmbNew.DisplayMemberPath = "Label.UserLocLabel.Label";
            this.cmbNew.SetBinding(ComboBox.SelectedItemProperty, base.GetBinding(this.RecordControl, this.ControlType, this.FieldName));
            
            this.cmbNew.IsEnabled= !recordControl.IsReadOnly;
         }


        #endregion

        #region Methods

        private IEnumerable<Option> GetOptions()
        {
            switch (this.DropdownType)
            {
                case DropdownType.Picklist:
                    return ((PicklistAttributeMetadata)this.AttrMeta).Options;
                case DropdownType.StatusReason:
                    return ((StatusAttributeMetadata)this.AttrMeta).Options.Cast<Option>();
                default:
                    throw new Exception("Unknown control type");
            }                     
        }


        public void FilterOptions(IEnumerable<int> allowedValues)
        {
            this.SelectableOptions.Clear();
            foreach (var item in this.GetOptions())
            {
                if (allowedValues.Contains(item.Value.Value))
                    this.SelectableOptions.Add(item);
            }
            //this.CreateNewComboBox();
        }

        private void ResetOptions()
        {
            this.SelectableOptions.Clear();
            this.SelectableOptions.AddRange(this.GetOptions());
            //this.CreateNewComboBox();
        }

        #endregion

        #region Events

        //private void cmbPicklist_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangedEventArgs e)
        //{
        //    if (cmbPicklist.SelectedValue != null)
        //    {
        //        if (this.AttrMeta.Description.UserLocLabel.Label.StartsWith("<filter>"))
        //        {
        //            XElement filter = XElement.Parse(this.AttrMeta.Description.UserLocLabel.Label);


        //            foreach (var r in filter.Elements("rule"))
        //            {
        //                bool ruleFound = false;
        //                foreach (var v in r.Elements("currentvalue"))
        //                {
        //                    if (v.Attribute("value").Value == cmbPicklist.SelectedValue.ToString())
        //                    {
        //                        var allowedValues = (from allowed in v.Elements("allowedvalue") select int.Parse(allowed.Attribute("value").Value));
        //                        if (this.RecordControl.RegisteredPicklists.ContainsKey(r.Attribute("targetpicklist").Value))
        //                            this.RecordControl.RegisteredPicklists[r.Attribute("targetpicklist").Value].FilterOptions(allowedValues);
        //                        ruleFound = true;
        //                    }
        //                }
        //                if (!ruleFound && this.RecordControl.RegisteredPicklists.ContainsKey(r.Attribute("targetpicklist").Value))
        //                    this.RecordControl.RegisteredPicklists[r.Attribute("targetpicklist").Value].ResetOptions();
        //            }
        //        }
        //    }
        //}
                
        private void cmbNew_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (cmbNew.SelectedItem != null)
            {
                if (this.AttrMeta.Description.UserLocLabel.Label.StartsWith("<filter>"))
                {
                    XElement filter = XElement.Parse(this.AttrMeta.Description.UserLocLabel.Label);


                    foreach (var r in filter.Elements("rule"))
                    {
                        bool ruleFound = false;
                        foreach (var v in r.Elements("currentvalue"))
                        {
                            if (v.Attribute("value").Value == (cmbNew.SelectedItem as Option).Value.Value.ToString())
                            {
                                var allowedValues = (from allowed in v.Elements("allowedvalue") select int.Parse(allowed.Attribute("value").Value));
                                if (this.RecordControl.RegisteredPicklists.ContainsKey(r.Attribute("targetpicklist").Value))
                                    this.RecordControl.RegisteredPicklists[r.Attribute("targetpicklist").Value].FilterOptions(allowedValues);
                                ruleFound = true;
                            }
                        }
                        if (!ruleFound && this.RecordControl.RegisteredPicklists.ContainsKey(r.Attribute("targetpicklist").Value))
                            this.RecordControl.RegisteredPicklists[r.Attribute("targetpicklist").Value].ResetOptions();
                    }
                }
            }
        }

        #endregion
    }
}
